package com.pet.user.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.common.domain.UserContext;
import com.pet.user.domain.po.Membership;
import com.pet.user.mapper.MembershipMapper;
import com.pet.user.service.IMembershipService;
import com.pet.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.pet.common.utils.RedisConstants.CACHE_MEMBERSHIP_KEY;

/**
 * <p>
 * 会员积分等级表 服务实现类
 * </p>
 *
 * @author Cookies
 * @since 2024-07-03
 */
@Service
@RequiredArgsConstructor
public class MembershipServiceImpl extends ServiceImpl<MembershipMapper, Membership> implements IMembershipService {
    private final StringRedisTemplate stringRedisTemplate;
    private final IUserService userService;

    @Override
    public List<Membership> queryMembershipList() {
        String key = CACHE_MEMBERSHIP_KEY;
        String jsonMembership = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(jsonMembership)) {
            return JSONUtil.toList(jsonMembership, Membership.class);
        }
        List<Membership> membershipList = lambdaQuery().list();
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(membershipList));
        return membershipList;
    }

    @Override
    public Integer queryDiscountByUser() {
        Integer userId = UserContext.getUser();
        Integer maxDiscount = 100;
        if (userId == null) {
            return maxDiscount;
        }
        Integer points = userService.getById(userId).getPoints();
        List<Membership> membershipList = queryMembershipList();
        for (Membership membership : membershipList) {
            if (points < membership.getMinPoints()) {
                break;
            }
            maxDiscount = membership.getDiscountRate();
        }
        return maxDiscount;
    }
}
